﻿using System;
using System.Net;
using System.Timers;

namespace Wusong.Gold.DataService
{
    public class ReaderBase : IDisposable
    {
        private WebClient client;
        Timer _timer;
        IResourceBase _resource;

        public delegate void AfterReadHandler(object sender, ReadEventArgs args);
        public event AfterReadHandler AfterRead;

        public ReaderBase(IResourceBase resource)
        {
            if (resource == null)
            {
                throw new ArgumentNullException("resource");
            }
            client = new WebClient();
            _resource = resource;
        }

        public void Start()
        {
            Read(null, null);
            if (_timer == null)
            {
                _timer = new Timer();
                _timer.Interval = 60000;
                _timer.AutoReset = true;
                _timer.Elapsed += new ElapsedEventHandler(Read);
            }

            _timer.Start();
        }

        public void Stop()
        {
            if (_timer != null)
                _timer.Close();
        }

        private void Read(object source, ElapsedEventArgs e)
        {
            try
            {
                string html = client.DownloadString(_resource.DataUri);
                if (string.IsNullOrEmpty(html))
                    return;

                GoldMsg msg = _resource.Formart(html);
                ReadEventArgs args = new ReadEventArgs(msg);
                if (AfterRead != null)
                {
                    AfterRead.Invoke(new object(), args);
                }

                Console.WriteLine(msg.FormatString);
            }
            catch (WebException wbEx)
            {
                Console.WriteLine(wbEx.Message);
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex);

            }

        }

        public void Dispose()
        {
            client.Dispose();
        }
    }

    public partial class ReadEventArgs : EventArgs
    {
        private GoldMsg _value;
        public GoldMsg Value
        {
            get
            {
                return _value;
            }
        }

        public ReadEventArgs(GoldMsg value)
        {
            _value = value;
        }
    }
}
